
layui.use(['jquery', 'form', 'layer'], function () {
    var $ = layui.jquery,
        form = layui.form,
        layer = layui.layer;

    window.openurl = function (title, url) {
        layer.open({
            type: 2,
            content: url,
            title: title,
            shade: false,
            maxmin: true, //开启最大化最小化按钮
            area: ['90%', '90%'],
            shadeClose: 1,
        });
    }


    $("body").on('blur', '.displayorder', function () {
        var url = $(this).attr('data-url');
        var id = $(this).attr('data-id');
        var value = $(this).val();
        displayOrder(id, value, adminpath + url);
    });

    //系统排序
    window.displayOrder = function (id, value, url) {
        // var displayorder = $(obj).val();
        var displayorder = value;
        if (!id || id == 'undefined' || !url || url == 'undefined') {
            return false;
        }
        $.post(url, { id: id, displayorder: displayorder }, function (res) {
            console.log(res);
            if (res.code == 0) {
                layer.msg('排序成功', { time: 1000, icon: 1 });
            } else {
                layer.msg(res.msg, { time: 2000, icon: 5 });
            }
        }, 'json');
    }

    window.open_parent_tab = function (title, url) {
        parent.openTabs({ title: title, url: url });
    }

    window.logout = function () {
        layer.confirm('确定退出吗？', { icon: 3, title: '提示' }, function (index) {
            $.post(adminpath + 'admin/login/out', {}, function (res) {
                layer.msg('退出成功', { icon: 1, time: 1000 }, function () {
                    window.location.reload();
                });
            }, 'json');
            layer.close(index);
        });
    }

    $(".logout").on('click', function () {
        logout();
    })

    form.on('checkbox(ams_select_all)', function (data) {
        if ($("#ams_select").prop("checked")) {
            $(".ams_select").prop("checked", true);
            form.render();
        } else {
            $(".ams_select").prop("checked", false);
            form.render();
        }
    });

    //表单
    form.on('checkbox(checkedf)', function (data) {
        if ($("#ams_check_" + data.value).prop("checked")) {
            $("#ams_check_" + data.value).prop("checked", false);
        } else {
            $("#ams_check_" + data.value).prop("checked", true);
        }
    });


    window.ams_tips = function (msg, time, code) {
        if (!msg || msg == '' || msg == '&nbsp;') {
            return
        }

        if (code == 0) {
            icon = 1
        } else {
            icon = 5
        }
        if (!time) {
            time = 1
        }

        layer.msg(msg, {
            time: time * 1000, //20s后自动关闭
            icon: icon,
        });
    }

    window.ams_confirm_url = function (title, url) {

        layer.confirm(title, {
            btn: ['确定', '取消'] //按钮
        }, function () {
            ams_tips(lang["waiting"], 3, 1);
            window.location.href = url;
            return true;
        }, function () {

        });
    }


    window.ams_confirm_set_all = function (title, del) {

        layer.confirm(title, {
            title: lang['tips'],
            btn: ['确定', '取消'] //按钮
        }, function (index, layero) {
            var _data = $("#myform").serialize();
            var _url = window.location.href;
            if ((_data.split("ids")).length - 1 <= 0) {
                d.close().remove();
                ams_tips(lang["select_null"]);
                return false;
            }

            $.ajax({
                type: "POST",
                dataType: "json",
                url: _url,
                data: _data,
                success: function (data) {
                    if (data.code == 1) {
                        ams_tips(data.msg, 3, 1);
                        if (del == 1) {
                            $(".ams_select").each(function () {
                                if ($(this).attr("checked")) {
                                    $("#ams_row_" + $(this).val()).remove()
                                }
                            });
                            layer.close(index);
                        } else {
                            setTimeout("window.location.reload(true)", 3000)
                        }
                    } else {
                        ams_tips(data.msg, 3, 2);
                        return true
                    }
                },
                error: function (HttpRequest, ajaxOptions, thrownError) { }
            });

        }, function () {
            //取消回调

        });
    }


    window.ams_selected = function () {
        if ($("#ams_select").prop("checked")) {
            $(".ams_select").prop("checked", true);
        } else {
            $(".ams_select").prop("checked", false);
        }
    }

    window.ams_selected_by = function (id) {
        if ($("#" + id).prop("checked")) {
            $("." + id).prop("checked", true);
        } else {
            $("." + id).prop("checked", false);
        }
    }

    window.ams_dialog_show = function (title, url) {
        $.ajax({
            type: "POST",
            dataType: "json",
            url: url,
            success: function (data) {
                layer.open({
                    type: 1,
                    title: title,
                    skin: 'layui-layer-demo', //样式类名
                    anim: 2,
                    shadeClose: true, //开启遮罩关闭
                    content: data
                });
            },
            error: function (HttpRequest, ajaxOptions, thrownError) { }
        })
    }

    /*
     * action: del删除 order排序 flag标记 move移动 update status 改变状态
     */
    window.ams_confirm_list_all = function (action, text) {

        if (!action) {
            layer.msg('参数错误：action没有传入');
            return false;
        }

        title = lang[action + '_all'] ? lang[action + '_all'] : lang['tips'];

        if (!text) {
            text = lang['confirm'];
        }

        layer.confirm(text, {
            title: title,
            btn: ['确定', '取消'] //按钮
        }, function () {
            //确定
            $('#action').val(action); //表单隐藏域
            var _data = $("#myform").serialize();
            if ((_data.split("ids")).length - 1 <= 0) {
                ams_tips(lang["select_null"], 2);
                return false;
            }

            var _url = window.location.href;
            $.ajax({
                type: "POST",
                dataType: "json",
                url: _url,
                data: _data,
                success: function (data) {
                    if (data.code == 1) {
                        ams_tips(data.msg, 2, 1);
                        setTimeout("window.location.reload(true)", 2000)
                    } else {
                        ams_tips(data.msg, 3, 2);
                        return true
                    }
                },
                error: function (HttpRequest, ajaxOptions, thrownError) { }
            });
        }, function () {
            //取消回调
        });
    }


    //批量删除
    $('#ams_confirm_del_all').click(function () {
        $('#action').val('del');
        var _data = $("#myform").serialize();
        var _url = window.location.href;
        if ((_data.split("ids")).length - 1 <= 0) {
            ams_tips(lang["select_null"], 2);
            return true
        }
        $.ajax({
            type: "POST",
            dataType: "json",
            url: _url,
            data: _data,
            success: function (data) {
                if (data.code == 1) {
                    ams_tips(data.msg, 2, 1);
                    setTimeout("window.location.reload(true)", 2000)
                } else {
                    ams_tips(data.msg, 3, 2);
                    top.$(".page-loading").remove();
                    return true
                }
            },
            error: function (HttpRequest, ajaxOptions, thrownError) { }
        });
        return true
    });

    $('#ams_confirm_set_all').click(function () {
        $('#action').val('del');
        var _data = $("#myform").serialize();
        var _url = window.location.href;
        if ((_data.split("ids")).length - 1 <= 0) {
            ams_tips(lang["select_null"], 2);
            return true
        }
        $.ajax({
            type: "POST",
            dataType: "json",
            url: _url,
            data: _data,
            success: function (data) {
                if (data.code == 1) {
                    ams_tips(data.msg, 3, 1);
                    setTimeout("window.location.reload(true)", 3000)
                } else {
                    ams_tips(data.msg, 3, 2);
                    return true
                }
            },
            error: function (HttpRequest, ajaxOptions, thrownError) { }
        });
        return true
    });

    //批量排序
    $('#ams_confirm_order').on(function () {
        $('#action').val('order');
        var _data = $("#myform").serialize();
        var _url = window.location.href;
        if ((_data.split("ids")).length - 1 <= 0) {
            ams_tips(lang["select_null"], 2);
            return true
        }
        $.ajax({
            type: "POST",
            dataType: "json",
            url: _url,
            data: _data,
            success: function (data) {
                if (data.code == 1) {
                    ams_tips(data.msg, 3, 1);
                    setTimeout("window.location.reload(true)", 3000)
                } else {
                    ams_tips(data.msg, 3, 2);
                    return true
                }
            },
            error: function (HttpRequest, ajaxOptions, thrownError) { }
        });
        return true
    });

    //批量修改状态
    $('#ams_confirm_verify').click(function () {
        $('#action').val('verify');
        var _data = $("#myform").serialize();
        var _url = window.location.href;
        if ((_data.split("ids")).length - 1 <= 0) {
            ams_tips(lang["select_null"], 2);
            return true
        }
        $.ajax({
            type: "POST",
            dataType: "json",
            url: _url,
            data: _data,
            success: function (data) {
                if (data.code == 1) {
                    ams_tips(data.msg, 3, 1);
                    setTimeout("window.location.reload(true)", 3000)
                } else {
                    ams_tips(data.msg, 3, 2);
                    top.$(".page-loading").remove();
                    return true
                }
            },
            error: function (HttpRequest, ajaxOptions, thrownError) { }
        });
        return true
    });

    window.ams_topinyin = function (name, from, letter) {
        var val = $("#ams_" + from).val();
        if ($("#ams_" + name).val()) {
            return false
        }
        $.get(memberpath + "?c=api&m=pinyin&name=" + val + "&rand=" + Math.random(), function (data) {
            $("#ams_" + name).val(data);
            if (letter) {
                $("#ams_letter").val(data.substr(0, 1))
            }
        })
    }


    window.ams_isemail = function (name) {
        var val = $("#ams_" + name).val();
        var reg = /^[-_A-Za-z0-9]+@([_A-Za-z0-9]+\.)+[A-Za-z0-9]{2,3}$/;
        if (reg.test(val)) {
            d_tips(name, true);
            return false
        } else {
            d_tips(name, false);
            return true
        }
    }

    window.ams_isurl = function (name) {
        var val = $("#ams_" + name).val();
        var reg = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
        var Exp = new RegExp(reg);
        if (Exp.test(val) == true) {
            d_tips(name, true);
            return false
        } else {
            d_tips(name, false);
            return true
        }
    }

    window.ams_isdomain = function (name) {
        var val = $("#ams_" + name).val();
        if (val.indexOf("/") > 0) {
            d_tips(name, false);
            return true
        } else {
            d_tips(name, true);
            return false
        }
    }

    window.ams_remove_file = function (name, id) {
        layer.confirm(lang["confirm"], {
            title: lang["tips"],
            btn: ['确定', '取消'],
            yes: function (index) {
                var fileid = $("#fileid_" + name + "_" + id).val();
                var value = $("#ams_" + name + "_del").val();
                $("#files_" + name + "_" + id).remove();
                $("#ams_" + name + "_del").val(value + "|" + fileid);
                layer.close(index);
            }
        });
    }

    window.ams_delete_file_js = function (name) {
        $("#ams_" + name).val("");
        $(".file_info_" + name).remove()
    }

    window.ams_delete_file = function (name) {

        layer.confirm(lang["confirm"], {
            title: lang["tips"],
            btn: ['确定', '取消'],
        }, function (index) {
            $("#ams_" + name).val("");
            $(".file_info_" + name).remove();
            layer.close(index);
        });
    }

    window.ams_delete_file2 = function (name) {
        layer.confirm('您确定要删除吗？', {
            btn: ['确定', '取消']
        }, function (index) {
            $("#fileid_" + name).val("");
            $("#ams_my_" + name + "_list").html("");
            layer.close(index);
        }, function () {

        });
    }

    window.ams_show_file_info = function (name) {
        var url = memberpath + "?c=api&m=fileinfo&name=" + name + "&rand=" + Math.random();
        layer.open({
            type: 2,
            shadeClose: true,
            area: ['450px', '450px'],
            title: lang["fileinfo"],
            content: url,
        });
    }

    window.ams_remove_ext = function (str) {
        var reg = /\.\w+$/;
        return str.replace(reg, "")
    }

    window.ams_get_block = function (id, i) {
        if (i == 1) {
            var html = '{' + 'ams_block(' + id + ')' + '}';
        } else if (i == 2) {
            var html = '{' + 'ams_block(' + id + ')' + '}';
        } else if (i == 3) {
            var html = '{' + 'ams_get_file(' + 'ams_block(' + id + ')' + ')}';
        } else if (i == 4) {
            var html = '{' + 'php $block=' + 'ams_block(' + id + ');' + '}';
            html += '<br>{';
            html += 'loop ';
            html += '$block';
            html += '.file $file}';
            //html+= '<br>{'+'loop'+' $block.file'+' file}';
            html += '<br>{' + 'ams_get_file($file' + ')}';
            html += '<br>{/' + 'loop ' + '}';
        }
        var body = '<div style="padding:20px;font-size:14px">' + html + '</div>';
        layer.alert(body);
    }

    window.ams_input_files = function (name, count) {
        var size = $("#" + name + "-sort-items li").length;
        var total = count - size;
        if (total <= 0) {
            ams_tips(fc_lang[42]);
            return
        }
        var id = size + 1;
        var url = memberpath + '?c=api&m=upload_input';
        $.ajax({
            type: "GET",
            url: url,
            dataType: "text",
            success: function (text) {
                layer.open({
                    type: 1,
                    title: lang["input"],
                    btn: ['确定', '关闭 '],
                    area: ['500px', '300px'],
                    content: text,
                    yes: function (index, layero) {
                        // console.log($(layero[0]).find("#ams_title").val());
                        var title = $(layero[0]).find("#ams_title").val();
                        var furl = $(layero[0]).find("#ams_url").val();
                        if (!title || !furl) {
                            ams_tips(fc_lang[43]);
                            return false
                        }
                        var c = "";
                        c += '<li id="files_' + name + "_" + id + '" list="' + id + '" class="ui-sortable-handle" style="cursor:move;">';
                        c += '<img src="' + furl + '" width="100" height="100" alt="' + title + '"/>';
                        c += '<input type="hidden" value="' + furl + '" name="data[' + name + '][file][]" id="fileid_' + name + "_" + id + '" />';
                        c += '<label class="files_name_input"><input type="text" class="form-control" style="width:300px;height:30px;" value="' + title + '" name="data[' + name + '][title][]" /></label>\t';
                        c += '<label class="uploader btn-shanchu"><a href="javascript:;" onclick="ams_remove_file(\'' + name + "','" + id + "')\">";
                        c += '<i class="fa fa-trash"></i></a></label>\t';
                        c += '<label class="uploader btn-yulan" id="span_' + name + '_' + id + '"><a href="javascript:;" onclick="ams_show_file_info(\'' + furl + "')\">";
                        c += '<i class="fa fa-search"></i></a></label>\t';
                        c += "</li>";
                        $("#" + name + "-sort-items").append(c);
                        ams_tips("操作成功", 1, 1);
                        layer.close(index);
                        return true
                    },
                    cancel: function () {
                        layer.close(index);
                        return true
                    }
                });
            },
            error: function (HttpRequest, ajaxOptions, thrownError) {
                ams_alert(HttpRequest.responseText)
            }
        })
    }

    window.ams_edit_file = function (url, name, id) {
        layer.open(lang["upload"], {
            type: 2,
            area: ['550', '400'],
            content: url,
            yes: function (index) {
                var iframe = window[layero.find('iframe')[0]['name']];
                if (!iframe.document.body) {
                    ams_tips("iframe loading");
                    return false
                }
                var value = iframe.document.getElementById("att-status").innerHTML;
                if (value == "" || value == undefined) {
                    ams_tips(lang["notselectfile"]);
                    return false
                } else {
                    var file = value.split("|");
                    var info = file[1].split(",");
                    $("#fileid_" + name + "_" + id).val(info[0]);
                    $("#span_" + name + "_" + id).html('<a href="javascript:;" class="btn btn-sm blue" onclick="ams_show_file_info(\'' + info[0] + '\')"><i class="fa fa-search"></i></a>');
                    layer.close(index);

                }
            },
            cancel: function () {
                return true
            }
        })
    }

    window.ams_edit_input_file = function (file2, title2, name, id) {
        var url = memberpath + '?c=api&m=upload_input&file=' + file2 + '&title=' + title2;
        $.ajax({
            type: "GET",
            url: url,
            dataType: "text",
            success: function (text) {
                layer.open({
                    title: lang["input"],
                    content: text,
                    area: ['500px', '300px'],
                    btn: ['确定', '关闭'],
                    yes: function () {
                        var title = top.$('#ams_title').val();
                        var furl = top.$('#ams_url').val();
                        if (!title || !furl) {
                            ams_tips(fc_lang[43]);
                            return false
                        }
                        var c = "";
                        c += '<div class="box box-solid"><input type="hidden" value="' + furl + '" name="data[' + name + '][file][]" id="fileid_' + name + "_" + id + '" />';
                        c += '<label><input type="text" class="form-control" style="width:300px;height:30px;" value="' + title + '" name="data[' + name + '][title][]" /></label>\t';
                        c += '<label><a href="javascript:;" class="btn btn-sm red" onclick="ams_remove_file(\'' + name + "','" + id + "')\">";
                        c += '<i class="fa fa-trash"></i></a></label>\t';
                        c += '<label><a href="javascript:;" class="btn btn-sm green" onclick="ams_edit_input_file(\'' + furl + "', '" + title + "', '" + name + "','" + id + "')\">";
                        c += '<i class="fa fa-edit"></i></a></label>\t';
                        c += '<label id="span_' + name + '_' + id + '"><a href="javascript:;" class="btn btn-sm blue" onclick="ams_show_file_info(\'' + furl + "')\">";
                        c += '<i class="fa fa-search"></i></a></label></div>\t';
                        $('#files_' + name + "_" + id + '').html(c);
                        return true
                    },
                    cancel: function () {
                        return true
                    }
                });
            },
            error: function (HttpRequest, ajaxOptions, thrownError) {
                ams_alert(HttpRequest.responseText)
            }
        })
    }

    $(".trigson").click(function () {
        var pid = $(this).attr('catid');
        if (pid && pid != 0) {
            if ($(".catid_" + pid).is(':hidden')) {
                $(this).text("[-]");
                $(".catid_" + pid).show();
            } else {
                $(this).text("[+]");
                $(".catid_" + pid).hide();
            }
        }
    });

    $(".navbar-nav .user-menu").mouseover(function () {
        $(".navbar-nav .user-menu").addClass('open');
    }).mouseout(function () {
        $(".navbar-nav .user-menu").removeClass('open');
    });

    // layer.open({
    //     type: 2,
    //     area: ['600px', '80%'],
    //     title: '修改产品',
    //     scrollbar: false,
    //     content: [adminpath + 'admin/product/edit?id=' + id, 'yes'],
    //     success: function (layero, index) {
    //         layer.iframeAuto(index);
    //     }
    // });

    window.ams_del_attach = function (fid) {
        $.post(adminpath + 'admin/uploads/delfile', { id: fid }, function (datas) { }, 'json');
    }

    //删除图片
    $("body").on('click', '.mokui-upload-item-delete', function () {
        var that = this;
        var obj = $(that).parent('.mokui-upload-item');
        var id = obj.attr('data-fileid');

        layer.confirm('确定删除吗？', { icon: 3, title: '提示' }, function (index) {
            if (id) {
                //文件id 服务器上删除
                $.post(adminpath + 'admin/uploads/delfile', { id, id }, function (res) {
                    if (res.code == 0) {
                        obj.remove();
                    } else {
                        layer.msg(res.msg, { time: 2000, anim: 6, icon: 6 });
                    }
                }, 'json')
            } else {
                obj.remove();
            }
            layer.close(index);
        });
    });

    //type 1整数 2小数 1. 整数：/^([^0][0-9]+|0)$/ 2. 小数：/^(([^0][0-9]+|0)\.([0-9]{1,2}))$/
    window.checkRate = function (type, nubmer) {
        if (type == 1) {
            var re = /^([^0][0-9]+|0)$/;
            if (!re.test(nubmer)) {
                return false;
            }
            return true;
        } else if (type == 2) {
            var re = /^(([^0][0-9]+|0)\.([0-9]{1,2})$)|^([^0][0-9]+|0)$/;
            if (!re.test(nubmer)) {
                return false;
            }
            return true;
        }
        return false;
    }

    window.ams_to_key = function () {
        $.get(adminpath + 'admin/opi/syskey', { id: 1 }, function (res) {
            if (res.code == 0) {
                $("#ams_sitekey").val(res.data);
            } else {
                layer.msg(res.msg, { time: 2000, anim: 6, icon: 6 });
            }
        }, 'json');
    }
});